(function($) {

	$.SJR = function(){};

	$.SJR.SIMPLE_JSON_REST = "1.0.0"

	$.SJR.option = {
		"type" : "",
		"url"  : "",
	};

	$.SJR.clear = function(){
		$.SJR.option.data = {};
		$.SJR.option.success = function(response, status){console.log('ajax success');};
		$.SJR.option.error = function(xhr, status, thrown){console.log('ajax error');};
	};
	$.SJR.clear();

	$.SJR.ajax = function() {
		$.ajax($.SJR.option);
	};

	$.SJR.ajaxbase = function(m, config, success, error){
		$.SJR.clear();
		if(Object.prototype.toString.call(config)!=='[object String]'){
			$.SJR.option = $.extend($.SJR.option, config);
		}else{
			$.SJR.option.data = config;
		}
		$.SJR.option.type = m;
		if(success) $.SJR.option.success = success;
		if(error) $.SJR.option.error = error;
		$.ajax($.SJR.option);
	};

	$.SJR.fn_extendbase = function(method, obj, success, error){
		if(!obj.attr('action')) return;
		var _success = function(response, status){
			$.SJR.response = response;
			$.SJR.status = status;
		};
		var _error = function(xhr, status, thrown){
			$.SJR.xhr = xhr;
			$.SJR.status = status;
			$.SJR.thrown = thrown;
		};
		$.SJR.option.url = obj.attr('action');
		var data = {"data" : obj.values()};
		$.SJR.ajaxbase(method, data, _success, _error);

		//メインここから
		//PUT時に問題あり。データは正常に更新できるが、画面上の表示が出来ない
		if($.SJR.status=='success'){
			if(method!=='DELETE'){
				obj.values($.SJR.response);
			} else {
				var val = obj.values();
				var tmp = {};
				for(var i in val)
					tmp[i]='';
				obj.values(tmp);
			}
			obj.__success = success;
			obj.__success();
			delete obj.__success;
		}else{
			obj.__error = error;
			obj.__error();
			delete obj.__error;
		}
		//メインここまで

		delete $.SJR.response;
		delete $.SJR.status;
		delete $.SJR.xhr;
		delete $.SJR.thrown;
	};

	$.extend({
		_GET : function(config, success, error) {
			$.SJR.ajaxbase("GET", config, success, error);
			return this;
		},
		_POST : function(config, success, error) {
			$.SJR.ajaxbase("POST", config, success, error);
			return this;
		},
		_PUT : function(config, success, error) {
			$.SJR.ajaxbase("PUT", config, success, error);
			return this;
		},
		_DELETE : function(config, success, error) {
			$.SJR.ajaxbase("DELETE", config, success, error);
			return this;
		}
	});
	$.fn.extend({
		_GET : function(success, error) {
			$.SJR.fn_extendbase('GET', this, success, error);
			return this;
		},
		_POST : function(success, error) {
			$.SJR.fn_extendbase('POST', this, success, error);
			return this;
		},
		_PUT : function(success, error) {
			$.SJR.fn_extendbase('PUT', this, success, error);
			return this;
		},
		_DELETE : function(success, error) {//jsonengineの場合、フォーム形式では削除できないので考える
			$.SJR.fn_extendbase('DELETE', this, success, error);
			return this;
		}
	});
})(jQuery);

